package com.lanou.horo.zhuizhui.fragment;


import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.lanou.horo.zhuizhui.activity.DialogActivity;

import com.lanou.horo.zhuizhui.activity.RecentComicsActivity;
import com.lanou.horo.zhuizhui.adapter.SearchIconAdapter;
import com.lanou.horo.zhuizhui.entity.HomePageItem;
import com.lanou.horo.zhuizhui.entity.PictureNewItem;
import com.lanou.horo.zhuizhui.entity.SearchIconItem;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.utility.slidingMenu.KeywordsFlow;
import com.lanou.horo.zhuizhui.utility.clickInterface.HomePageItemClickListener;
import com.lanou.horo.zhuizhui.utility.clickInterface.ItemLongClickListener;
import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.utility.recyclerView.SpacesItemDecoration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class SearchPageFragment extends Fragment implements HomePageItemClickListener, ItemLongClickListener,
        SwipeRefreshLayout.OnRefreshListener,  View.OnClickListener {
    private KeywordsFlow keywordsFlow;
    private EditText searchEditText, visibilityEditText;
    private TextView searchMoreTextView,searchvBack;
    private Button searchInTextView;
    private RelativeLayout searchRelativeLayout;
    private LinearLayout searchLinearLayout;
    private RecyclerView recyclerView;
    private SearchIconAdapter adapter;
    private RequestQueue queue;
    private SwipeRefreshLayout swipeRefreshWidget;
    private int lastVisibleItem;
    private boolean isdialogshowing = false;
    private CustomProgressDialog dialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    swipeRefreshWidget.setRefreshing(false);
                    if (adapter.getEntities() != null) {
                        adapter.getEntities().clear();
                        initData();
                    }
                    break;
            }
        }
    };
    ;
    public static final String[] keywords = {"鲇川丸子《橙路》",
            "柳叶雅美《非常家庭》",
            " 阿香《侠探寒羽良》",
            "拉姆《福星小子》",
            " 阿雪《福星小子》",
            "美神令子《极乐美神大作战》",
            " 阿拉蕾 《阿拉蕾》",
            " 城户纱织/雅典娜《圣斗士星矢》",
            " 赤木晴子《灌蓝高手》",
            " 黑主优姬《吸血鬼骑士》",
            " 阿娅《寄生前夜》",
            "  霞《生与死》",
            " 春丽《街霸》",
            " 黄步 铃（东京喵喵）",
            " 铃木 园子（名侦探柯南）",
            " 花铃（小女神花铃）",
            " 神尾 观铃（AIR）",
            " 李 莓铃（魔卡少女樱）",
            " 铃（犬夜叉）",
            " 小铃（蓝兰岛漂流记）",
            " 美玲·霍克（高达Destiny）",
            " 草壁 美铃（11 eyes 罪与罚与赎的少女）",
            " 草摩 依铃（水果篮子）",
            " 铃仙·优昙华院·因幡（东方系列）",
            " 魔铃（圣斗士星矢）",
            " 香铃（彩云国物语）",
            " 翠铃、铃原 花音（风之圣痕）",
            " 果铃（蔷薇少女）",
            " 红玉 铃子（宝石宠物）",
            " 夏木 铃（Yes!光之美少女5）"};


    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_search, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.searchIconRecyclerView);
        swipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.searchSwipeRefresh);
        searchEditText = (EditText) view.findViewById(R.id.searchEditText);
        keywordsFlow = (KeywordsFlow) view.findViewById(R.id.keywordsFlow);
        searchvBack = (TextView) view.findViewById(R.id.searchvBack);
        searchInTextView = (Button) view.findViewById(R.id.searchInTextView);
        searchLinearLayout = (LinearLayout) view.findViewById(R.id.searchLinearLayout);
        searchRelativeLayout = (RelativeLayout) view.findViewById(R.id.searchRelativeLayout);
        searchMoreTextView = (TextView) view.findViewById(R.id.searchMoreTextView);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        keywordsFlow.setDuration(800l);
        keywordsFlow.setOnItemClickListener(this);
        searchInTextView.setOnClickListener(this);
        searchMoreTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchLinearLayout.setVisibility(View.VISIBLE);
                searchRelativeLayout.setVisibility(View.INVISIBLE);
            }
        });
        searchvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchLinearLayout.setVisibility(View.INVISIBLE);
                searchRelativeLayout.setVisibility(View.VISIBLE);
            }
        });
        // 添加
        feedKeywordsFlow(keywordsFlow, keywords);
        keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);



//        searchEditText.setOnFocusChangeListener(this);
//        visibilityEditText.setOnFocusChangeListener(this);
        dialog = new CustomProgressDialog(getActivity(), "加载中...", R.anim.loding);
        dialog.setCanceledOnTouchOutside(false);
        swipeRefreshWidget.setColorSchemeColors(0xff00aa00, 0xfffedcba, 0xff123456, 0xff654321);
        swipeRefreshWidget.setOnRefreshListener(this);


        swipeRefreshWidget.setProgressViewOffset(false, -10, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
                        .getDisplayMetrics()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        swipeRefreshWidget.setProgressViewEndTarget(true, 100);


        int spacingInPixels = 20;
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
        adapter = new SearchIconAdapter(getContext());
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);
        adapter.setItemClickListener(this);
        adapter.setLongClickListener(this);


    }

    private static void feedKeywordsFlow(KeywordsFlow keywordsFlow, String[] arr) {
        Random random = new Random();
        for (int i = 0; i < KeywordsFlow.MAX; i++) {
            int ran = random.nextInt(arr.length);
            String tmp = arr[ran];
            keywordsFlow.feedKeyword(tmp);
        }
    }


    private void initData() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        queue = Volley.newRequestQueue(getContext());
        String url = "http://api.zhuizhuiyoyo.com/request.php?method=searchpage&timestamp=" +
                "1446087839014&param=%7B%22v%22%3A1%2C%22t%22%3A0%7D&sig=20568f7aeee455508c1812ef602c9f3a";
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gson = new Gson();
                SearchIconItem sii = gson.fromJson(response, SearchIconItem.class);
                if (sii != null) {
                    List<SearchIconItem.ThemesEntity> entities = sii.getThemes();
                    if (entities != null && entities.size() > 0) {
                        adapter.addSeaList(entities);

                    }
                }

                swipeRefreshWidget.setRefreshing(false);
                if (isdialogshowing == true) {
                    dialog.dismiss();
                    isdialogshowing = false;
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);
    }


    @Override
    public void homePageItemClick(HomePageItem.ListsEntity hlid) {
    }

    @Override
    public void pictureItemClick(PictureNewItem.WelfaresEntity pnwe, int itemPosition, List<String> imgUrl, ImageView imageView) {
    }


    @Override
    public void searcherItemClick(SearchIconItem.ThemesEntity stid) {
        int pageId = stid.getTheme_info().getId();
        Toast.makeText(getActivity(), "stid.getTheme_info().getId():" + stid.getTheme_info().getId(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        if (pageId == 38 || pageId == 39 || pageId == 116 || pageId == 1047) {
            intent.setClass(getActivity(), RecentComicsActivity.class);
            intent.putExtra("id", stid.getTheme_info().getId());
            startActivity(intent);
        }
    }

    @Override
    public void homeItemClick(HomePageItem.ListsEntity.ThemeListEntity hlt) {

    }

    @Override
    public void searcherItemLongClick(SearchIconItem.ThemesEntity entity) {
        int pageId = entity.getTheme_info().getId();
//        Toast.makeText(getActivity(), "entity.getTheme_info().getId():" +
//                entity.getTheme_info().getId(), Toast.LENGTH_SHORT).show();

        Intent intent = new Intent();
        if (pageId == 38 || pageId == 39 || pageId == 116 || pageId == 1047) {
            intent.setClass(getActivity(), DialogActivity.class);
            intent.putExtra("id", entity.getTheme_info().getId());
            startActivity(intent);
        }
    }

    @Override
    public void onRefresh() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        handler.sendEmptyMessageDelayed(0, 3000);
    }

    public void showProgressDialog() {
        final ProgressDialog pd = new ProgressDialog(getActivity());
        pd.setMessage("加载中...");

        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        pd.setMax(100);

        pd.show();
        final Intent QQintent = new Intent();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    handler.sendEmptyMessageDelayed(0, 0);
                    pd.dismiss();//关闭ProgressDialog
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

//    @Override
//    public void onFocusChange(View v, boolean hasFocus) {
//        if (hasFocus) {
//            //得到焦点
//            switch (v.getId()) {
//                case R.id.searchEditText:
//                    searchLinearLayout.setVisibility(View.VISIBLE);
//                    searchRelativeLayout.setVisibility(View.INVISIBLE);
//                    break;
//            }
//        } else {
//            //失去焦点
//
//        }
//    }

    @Override
    public void onClick(View v) {
        if (v == searchInTextView) {
            keywordsFlow.rubKeywords();
            // keywordsFlow.rubAllViews();
            feedKeywordsFlow(keywordsFlow, keywords);
            keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);
        } else if (v instanceof TextView) {
            String keyword = ((TextView) v).getText().toString();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse("http://www.google.com.hk/#q=" + keyword));
            startActivity(intent);
        }
    }
}


